package com.example.user.customviewdemo.drawing.xfermode;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.view.View;

import com.example.user.customviewdemo.R;

/**
 * Created by user on 2016/5/5.
 * 利用Matrix制作图片倒立bitmap，然后利用PorterDuffXfermode 的Mode.SRC_IN制作如水中倒影图像
 */
public class RevertBitmapView extends View {
    private Bitmap bmp, revertBmp, dstBmp;
    private Paint paint;

    public RevertBitmapView(Context context) {
        super(context);
    }

    public RevertBitmapView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        paint.setAntiAlias(true);

        bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.dog);
        // dstBmp = BitmapFactory.decodeResource(getResources(),R.mipmap.alpha);

        // 利用Matrix的setScale（）方法制作倒立图像
        Matrix m = new Matrix();
        m.setScale(1F, -1F);

        revertBmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), m, true);
        dstBmp = Bitmap.createBitmap(revertBmp.getWidth(), revertBmp.getHeight(), Bitmap.Config.ARGB_8888);

    }

    public RevertBitmapView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(0xff293134);

        //绘制原图
        canvas.drawBitmap(bmp, 0, 0, paint);

        //得到一个alpah分布不同的dstBmp
        Canvas c = new Canvas(dstBmp);
        float x = dstBmp.getHeight() / 100;
        Paint paint1 = new Paint();
        paint1.setColor(Color.RED);
        paint1.setAntiAlias(true);
        paint1.setStyle(Paint.Style.FILL);
        for (int i = 100; i >= 0; i--) {
            paint1.setAlpha(i);
            c.drawRect(0, (99 - i) * x, dstBmp.getWidth(), (100 - i) * x, paint1);
        }

        //透明度没起作用，估计是dstBmp的透明度没有变化的原因
        int layerID = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG);
        canvas.translate(0, bmp.getHeight());
        canvas.drawBitmap(dstBmp, 0, 0, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(revertBmp, 0, 0, paint);
        paint.setXfermode(null);
        canvas.restoreToCount(layerID);
    }
}
